from django.db import models
from django.utils import timezone


class BaseModel(models.Model):
    is_deleted = models.BooleanField(default=False, verbose_name="是否删除")
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    update_time = models.DateTimeField(null=True, blank=True, verbose_name="更新时间")
    delete_time = models.DateTimeField(null=True, blank=True, verbose_name="删除时间")

    def soft_delete(self):
        self.is_deleted = True
        self.delete_time = timezone.now()
        self.save()

    def restore(self):
        self.is_deleted = False
        self.delete_time = None
        self.save()

    @classmethod
    def activate_objects(cls):
        return cls.objects.filter(is_deleted=False)

    @classmethod
    def delete_objects(cls):
        return cls.objects.filter(is_deleted=True)

    class Meta:
        abstract = True
        ordering = ["-create_time"]
        indexes = [
            models.Index(fields=["create_time"], name="idx_create_time"),
            models.Index(fields=["is_deleted"], name="idx_is_deleted"),
        ]
